package com.lqq.chapter08;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author lqq677
 * @Date 2021/8/11 21:06
 * @Description coding
 */

//资源类
class MyCache {

    //Map集合，存放数据
    private volatile Map<String, Object> map = new HashMap();

    //创建读写锁对象
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();//读锁
    private ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();//写锁

    //写数据
    public void write(String key, Object value) {

        //上写锁
        writeLock.lock();

        try {
            System.out.println(Thread.currentThread().getName()+" 正在写操作" + key);

            //暂停一会
            TimeUnit.MILLISECONDS.sleep(300);

            //放数据
            map.put(key, value);
            System.out.println(Thread.currentThread().getName()+" 写完了" + key);

        } catch (InterruptedException e) {
            e.printStackTrace();

        } finally {
            //释放写锁
            writeLock.unlock();
        }

    }


    //读取数据
    public Object read(String key) {

        //上读锁
        readLock.lock();

        Object result = null;

        try {
            System.out.println(Thread.currentThread().getName()+" 正在读取操作" + key);

            //暂停一会
            TimeUnit.MILLISECONDS.sleep(200);

            //读数据
            result = map.get(key);
            System.out.println(Thread.currentThread().getName()+" 读取完了" + result);

        } catch (InterruptedException e) {
            e.printStackTrace();

        } finally {
            //释放写锁
            readLock.unlock();
        }

        return result;
    }

}

public class ReadWriteLockDemo {
    public static void main(String[] args) throws InterruptedException {

        MyCache myCache = new MyCache();

        //写线程写数据
        for (int i = 1; i <= 5; i++) {
            final int key = i;
            final int value = i;
            new Thread(() ->{
                myCache.write(key+"", value+"");
                    }, String.valueOf(i)).start();
        }

        TimeUnit.MILLISECONDS.sleep(100);

        //读线程
        for (int i = 1; i <= 5; i++) {
            final int key = i;
            new Thread(() ->{
                myCache.read(key+"");
            }, String.valueOf(i)).start();
        }
    }
}
